package ca.uwo.android.rss.news;

/**
 * This class represents an Rss News Feed that stores Rss Items from various modules
 * in the iWestern application.
 * @author Chirag Mistry
 */


import java.io.IOException;
import java.net.MalformedURLException;

import org.xml.sax.SAXException;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Spanned;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import ca.uwo.android.BaseListMenuActivity;
import ca.uwo.android.R;
import ca.uwo.android.rss.RssFeed;
import ca.uwo.android.rss.RssItem;
import ca.uwo.android.rss.SaxRssParser;
import android.util.Log;

public class RssNewsFeed extends BaseListMenuActivity {
	
	private String url; // url of rss feed
	private RssFeed rssResults; // rss feed to store rss items from feed

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newsfeedmain);

		// get the url, feed type and header title from framework
		String url = getIntent().getExtras().getString("URL");
		String newsFeedHeader = getIntent().getExtras().getString("HEADER");

		// initialize required attributes
		this.url = url;
		((TextView) findViewById(R.id.newsFeedHeader)).setText(newsFeedHeader);

		loadRssFeed(); // connect, retrieve, parse and display the rss feed data

		ListView lv = getListView();
		lv.setOnItemClickListener(new OnItemClickListener() {

			/**
			 * This method is used to redirect the user to the appropriate
			 * website with more information about the news headline that was
			 * clicked. If the Mustang News module is running, it will redirect
			 * the user to a custom view that will display scraped content from
			 * the web, pertaining to the news headline clicked.
			 * 
			 * @param view
			 *            the text view that was clicked
			 * @param position
			 *            the index of the clicked item in the list view
			 */
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				RssItem clickedItem = rssResults.get(position); // get clicked
																// item
				String clickedItemUrl = clickedItem.getLink(); // get url for
																// clicked item

				Intent openFeedUrl = new Intent(Intent.ACTION_VIEW, Uri
						.parse(clickedItemUrl));
				startActivity(openFeedUrl);
			}
		});
	}

	/**
	 * This method is used to connect to, retrieve, parse and display the rss
	 * feed data from a rss feed url.
	 */
	public void loadRssFeed() {
		try {
			// retreive and parse the rss feedLog.
			SaxRssParser rssParser = new SaxRssParser(url);
			rssResults = rssParser.parse();

			Spanned[] feeds = new Spanned[rssResults.size()];

			// store the rss item descriptions to display in the feed as spanned
			// objects
			for (int i = 0; i < rssResults.size(); i++) {
				feeds[i] = rssResults.get(i).toNewsString();
			}

			// create list adapter
			ArrayAdapter<Spanned> adapter = new ArrayAdapter<Spanned>(this,
					R.layout.newsfeeditem, R.id.newsFeedItemTextView, feeds);

			this.setListAdapter(adapter); // populate list with adapter

		} catch (Exception e) {

			// Log.e("RssNewsFeed loadRssFeed", "Exception reading feed", e);

			// create empty alert dialog
			AlertDialog alert = new AlertDialog.Builder(RssNewsFeed.this)
					.setTitle("Error")
					.setIcon(android.R.drawable.ic_dialog_alert)
					.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									finish(); // close the current activity and
												// return to the previous one
								}
							}).create();

			// Error checking
			if (e instanceof MalformedURLException) {
				alert.setMessage("The URL for the RSS feed is invalid!");
			} else if (e instanceof SAXException) {
				alert.setMessage("The RSS feed could not be parsed!");
				e.printStackTrace();
				// Log.e("RssNewsFeed", "Error parsing:  " + e.getMessage());
			} else if (e instanceof IOException) {
				alert.setMessage("Could not establish a connection to the RSS feed!");
			} else {
				alert.setMessage("There was a problem while parsing the RSS feed!");
			}
			alert.show(); // show populated alert dialog based on error type
		}
	}
}
